<!--注意id属性每个页面id必须独立，lay-title为当前页面的标题属性-->
<div class="layui-fluid layui-anim febs-anim" id="notice-list" lay-title="通知列表">
    <div class="layui-row febs-container">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body febs-table-full">
                    <!--注意lay-filter属性，该属性为form表单唯一属性-->
                    <form class="layui-form layui-table-form" lay-filter="user-table-form" id="selectForm">
                        <!--fieldset为区分搜索区域-->
                        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">
                            <legend style="font-size: 15px; font-weight: bolder;">批量查询</legend>
                        </fieldset>
                        <div class="layui-row">
                            <div class="layui-col-md11">
                                <!-- layui-form-item为自适应长度样式 -->
                                <div class="layui-form-item">
                                    <!-- layui-inline样式为单行多控件 -->
                                    <div class="layui-inline">
                                        <label class="layui-form-label layui-form-label-sm">通知标题</label>
                                        <div class="layui-input-inline">
                                            <input type="text" id="txtTitle" name="title" autocomplete="off"
                                                   class="layui-input" lay-verify="txt" maxlength="13">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label layui-form-label-sm">创建人</label>
                                        <div class="layui-input-inline">
                                            <div class="layui-input-inline">
                                                <input type="text" name="createUserId" id="cboTeachery"
                                                       lay-filter="cboTeachery" class="layui-input">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- 查询重置按钮 -->
                            <!-- 注意id属性 用于绑定JS事件-->
                            <div class="layui-col-md1 layui-col-sm12 layui-col-xs12 table-action-area">
                                <div class="layui-btn layui-btn-sm layui-btn-primary febs-button-blue-plain
                                            table-action" id="btnSearch" title="查询" lay-submit
                                     lay-filter="noticeQuery-form-submit">
                                    <i class="layui-icon">&#xe848;</i>
                                </div>
                                <div class="layui-btn layui-btn-sm layui-btn-primary febs-button-green-plain
                                            table-action" id="btnReset" title="重置">
                                    <i class="layui-icon">&#xe79b;</i>
                                </div>
                            </div>
                        </div>
                    </form>
                    <!-- 表格 -->
                    <!-- 注意lay-filter和id属性，两者需保持一致 用于绑定JS事件-->
                    <table lay-filter="noticeTable" lay-data="{id: 'noticeTable'}"></table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 列表头部工具栏 -->
<!-- 注意id属性，列表初始化的时候加载列表头部工具栏-->
<script type="text/html" id="toolComponents">
    <!-- 注意id属性，用于绑定JS事件-->
    <div class="layui-btn layui-btn-sm layui-btn-primary febs-button-blue-plain table-action"
         lay-event="btnCreateNotice">
        <i class="layui-icon layui-icon-plus-circle"></i>新增
    </div>
    <!-- 注意id属性，用于绑定JS事件-->
    <div class="layui-btn  layui-btn-sm layui-btn-primary febs-button-green-plain "
         lay-event="notice-export">
        <i class="layui-icon layui-icon-export"></i>导出
    </div>
</script>
<!-- 此项配合初始化表格中列的templet属性使用-->
<script type="text/html" id="notice-status">
    {{#
    let status = {
    1: {title: '已发布', color: 'green'},
    0: {title: '草稿', color: 'volcano'}
    }[d.status];
    }}
<span class="layui-badge febs-bg-{{status.color}}">{{ status.title }}</span>
</script>
<script data-th-src="@{/aliyunUpload/lib/es6-promise.min.js}"></script>
<script data-th-src="@{/aliyunUpload/lib/aliyun-oss-sdk-6.13.0.min.js}"></script>
<script data-th-src="@{/aliyunUpload/aliyun-upload-sdk-1.5.2.min.js}"></script>
<script type="text/javascript" src="module/treeSelect/treeSelect.js"></script>
<script data-th-inline="none" type="text/javascript">
    layui.use(['treeSelect', 'dropdown', 'jquery','util','laydate', 'form', 'table', 'febs', 'xmSelect', 'validate'], function () {
        let $ = layui.jquery,
            util = layui.util,
            treeSelect = layui.treeSelect,
            febs = layui.febs,
            form = layui.form,
            table = layui.table,
            // 定义页面视图
            $view = $('#notice-list'),
            // 定义查询按钮
            $btnSearch = $view.find('#btnSearch'),
            // 定义重置按钮
            $btnReset = $view.find('#btnReset'),
            // 定义form表单
            $searchForm = $view.find('form'),
            // 定义表格排序
            sortObject = {field: 'createTime', type: null},
            tableIns,
            validate = layui.validate,
            createTimeFrom,
            createTimeTo;
        let lock = false;
        // 表单验证
        form.verify(validate);
        // 表单渲染
        form.render();

        //构建用户树
        treeSelect.render({
            // 选择器
            elem: '#cboTeachery',
            // 数据
            data: ctx + 'notice/userDeptTree',
            // 异步加载方式：get/post，默认get
            type: 'get',
            // 占位符
            placeholder: '请选择',
            // 是否开启搜索功能：true/false，默认false
            search: true,
            style: {
                folder: { // 父节点图标
                    enable: true // 是否开启：true/false
                },
                line: {
                    enable: true
                }
            },
            // 点击回调
            click: function (d) {
                $("#cboTeachery").val(d.current.id);
            },
            // 加载完成后的回调函数
            success: function (d) {

            }
        });
        // 调用列表初始化方法
        initTable();

        // 查询按钮点击事件
        form.on('submit(noticeQuery-form-submit)', function (data) {
            if (!lock) {
                lock = true;
                let params = $.extend(getQueryParams(), {field: sortObject.field, order: sortObject.type});
                tableIns.reload({where: params, page: {curr: 1}});
                setTimeout(function () {
                    lock = false;
                }, 800);
            }
            return false;
        });
        //重置
        $btnReset.on('click', function () {
            if (!lock) {
                lock = true;
                $searchForm[0].reset();
                sortObject.type = 'null';
                tableIns.reload({where: getQueryParams(true), page: {curr: 1}, initSort: sortObject});
                setTimeout(function () {
                    lock = false;
                }, 800);
            }
        });

        //创建人下拉菜单
        $.ajax({
            type: 'get',
            url: ctx + 'user/selectUserlist',
            cache: false,
            success: function (res) {
                let userArray = res.data.rows;
                if (userArray.length > 0) {
                    for (let i = 0; i < userArray.length; i++) {
                        let user = userArray[i];
                        $("#cboTeachery").append("<option value='" + user.userId + "'>" + user.username + "</option>");
                    }
                }
                layui.form.render("select");
                $.ajax({
                    type: 'get',
                    url: 'notice/findCreateUserId',
                    success: function (res) {
                        $("#cboTeachery").val(res.data);
                        layui.form.render("select");
                    }
                })
            }

        });

        function initTable() {
            tableIns = febs.table.init({
                elem: $view.find('table'),
                id: 'noticeTable',
                url: ctx + 'notice/foundNoticeSelect',
                done: function (res, curr, count) {
                    $("table").css("width", "100%");
                },
                width: "100%",
                toolbar: '#toolComponents',
                defaultToolbar: ['filter'],
                cols: [[
                    {field: 'id', title: '编号', width: 100},
                    {field: 'title', title: '通知标题', minWidth: 240,templet: function(d){
                            return util.escape(d.title);
                        }},
                    {field: 'userName', title: '创建人'},
                    {field: 'createTime', title: '创建时间', minWidth: 180},
                    {field: 'countShouldRead', title: '应读', width: 100},
                    {field: 'countRead', title: '已读', width: 100},
                    {title: '状态', templet: '#notice-status', width: 100},
                ]],
            });
        }

        //新增、导出
        table.on('toolbar(noticeTable)', function (obj) {
            switch (obj.event) {
                case 'btnCreateNotice':
                    febs.modal.open('新建通知', 'notice/add', {
                        btn: ['创建', '保存草稿', '取消'],
                        resize: false,
                        area: $(window).width() <= 750 ? ['90%', '100%'] : ['50%', '100%'],
                        yes: function (index, layero) {
                            febs.modal.confirm('提示', '确定创建通知并发送？', function () {
                                $('#notice-add').find('#status_Id').val(1);
                                $('#notice-add').find('#submit').trigger('click');
                            });
                        },
                        btn2: function () {
                            $('#notice-add').find('#status_Id').val(0);
                            $('#notice-add').find('#submitTemp').trigger('click');
                            return false;
                        },
                        btn3: function () {
                            $('#notice-add').find('#reset').trigger('click');
                        }
                    });
                    break;
                case 'notice-export':
                    if (!lock) {
                        lock = true;
                        let params = $.extend(getQueryParams(), {field: sortObject.field, order: sortObject.type});
                        params.pageSize = $view.find(".layui-laypage-limits option:selected").val();
                        params.pageNum = $view.find(".layui-laypage-em").next().html();
                        let d = new Date();
                        let year = d.getFullYear(); // 年
                        let month = d.getMonth() + 1; // 月
                        let day = d.getDate(); // 日
                        let hour = d.getHours(); // 时
                        let minutes = d.getMinutes(); // 分
                        let seconds = d.getSeconds(); //秒
                        if (month >= 1 && month <= 9) {
                            month = "0" + month;
                        }
                        if (day >= 0 && day <= 9) {
                            day = "0" + day;
                        }
                        if (hour >= 0 && hour <= 9) {
                            hour = "0" + hour;
                        }
                        if (minutes >= 0 && minutes <= 9) {
                            minutes = "0" + minutes;
                        }
                        if (seconds >= 0 && seconds <= 9) {
                            seconds = "0" + seconds;
                        }
                        let date = "" + year + month + day + '_' + hour + minutes + seconds;
                        let time = '通知信息' + date + '.xlsx';
                        febs.download(ctx + 'notice/excel', params, time);
                        setTimeout(function () {
                            lock = false;
                        }, 2000);
                    }
                    break;
            }
        });
        //表格中操作栏按钮
        table.on('tool(noticeTable)', function (obj) {
            console.log(obj.data);
            let data = obj.data,
                layEvent = obj.event;
            if (layEvent === 'edit') {
                febs.modal.open('编辑通知', 'businesses/noticeEdit/' + data.id, {
                    btn: ['提交', '取消'],
                    resize: false,
                    area: $(window).width() <= 400 ? '95%' : ['50%', '80%'],
                    yes: function (index, layero) {
                        febs.modal.confirm('提示', '确定修改该通知？', function () {
                            $('#notice-edit').find('#btnPreservation').trigger('click');
                        });
                    },
                    btn2: function (index, layero) {
                        layer.closeAll();
                    }
                });
            }
            if (layEvent === 'del') {
                febs.modal.confirm('提示', '确定删除该通知？', function () {
                    deleteNotice(data.id)
                    tableIns.reload();
                });
            }
            /**
             * 修改
             */
            if (layEvent === 'release') {
                febs.modal.confirm('提示', '确定发送该通知？', function () {
                    $.ajax({
                        type: 'post',
                        url: 'notice/update',
                        data: {"id": data.id, "classId": data.classId},
                        success: function (res) {
                            tableIns.reload();
                        }
                    })
                });
            }

            if (layEvent === 'detail') {
                let index = febs.modal.open('通知详情', 'businesses/noticeDetail/' + data.id, {
                    area: $(window).width() <= 750 ? '90%' : '50%',
                    resize: false,
                    btn: ['关闭'],
                    yes: function (index, layero) {
                        layer.closeAll()
                    }
                });
            }

            if (layEvent === 'statistics') {
                febs.modal.open('统计详情', 'noticeUser/statistics/' + data.id, {
                    resize: false,
                    area: ['70%', '80%'],
                    btn: ['关闭'],

                    btn2: function () {
                        layer.closeAll();
                    }
                });
            }


        })


        function getQueryParams(flag) {
            let batchName = $("#cboBatchy").val();
            let collegeName = $("#cboCollegey").val();
            let majorName = $("#cboMajory").val();
            let levelName = $("#cboLevely").val();
            let title = $("#txtTitle").val();
            let params = $searchForm.serializeJson();
            if (flag) {

            }
            let createUserId = $("#cboTeachery").val();
            params.createUserId = createUserId;
            params.batchId = batchName;
            params.collegeName = collegeName;
            params.majorName = majorName;
            params.levelName = levelName;

            params.title = title;
            let createTime = params.time;
            if (createTime) {
                createTimeFrom = createTime.split(' - ')[0];
                createTimeTo = createTime.split(' - ')[1];
            }
            params.invalidate_ie_cache = new Date();
            return params;
        }

        function deleteNotice(noticeId) {
            febs.get(ctx + 'notice/deleteById/' + noticeId, null, function () {
                febs.alert.success('删除通知成功');
                $btnSearch.click();
            });
        }

        //按回车搜索
        $(".layui-input").keyup(function (e) {//当按下按键时
            if (e.which === 13) {//.which属性判断按下的是哪个键，回车键的键位序号为13
                $btnSearch.click();
            }
        });

        //文本框内容转义
        function HTMLEncode(html) {
            var temp = document.createElement("div");
            (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
            var output = temp.innerHTML;
            temp = null;
            return output;
        }


        //文本框内容反转义
        function HTMLDecode(text) {
            var temp = document.createElement("div");
            temp.innerHTML = text;
            var output = temp.innerText || temp.textContent;
            temp = null;
            return output;
        }
    })
</script>